/*
 * @Author: your name
 * @Date: 2020-05-06 09:50:38
 * @LastEditTime: 2020-06-04 14:22:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \museweb\src\views\musePage\mixins\uploadMixin.js
 */ 
const COS = require('cos-js-sdk-v5');
import  { getAuthorization } from '@/api/admin'
export default {
  data () {
    return {
      cos: null
    }
  },
  created () {
    this.cos = new COS({
      // 必选参数
      getAuthorization: async (options, callback) => {
        const {data} = await getAuthorization({
          bucket: process.env.VUE_APP_BUCKET,
          region: process.env.VUE_APP_REGION
        })
        callback({
          TmpSecretId: data.credentials.tmpSecretId,
          TmpSecretKey: data.credentials.tmpSecretKey,
          XCosSecurityToken: data.credentials.sessionToken,
          ExpiredTime: data.expiredTime, // SDK 在 ExpiredTime 时间前，不会再次调用 getAuthorization
        })
      }
    });
  },
  methods: {
    // 上传
    fnUpload(fileObj) {
      // return URL.createObjectURL(fileObj.file);
      return new Promise((resolve, reject) => {
        const file = fileObj.file
        const fileName = `${new Date().getTime()}${file.name}`
        this.cos.putObject({
          Bucket: process.env.VUE_APP_BUCKET, /* 必须 */
          Region: process.env.VUE_APP_REGION,    /* 必须 */
          Key: process.env.VUE_APP_UPLOAD_PATH + fileName,              /* 必须 */
          Body: file, // 上传文件对象
          onProgress: (progressData) => {
            if(progressData.percent === 1) {
              const url = `https://${process.env.VUE_APP_BUCKET}.cos.${process.env.VUE_APP_REGION}.myqcloud.com${process.env.VUE_APP_UPLOAD_PATH}${fileName}`
              resolve(url)
            }
          }
        }, function(err, data) {
          reject(err || data)
        });
      })
    }
  }
}
